//
//  VC_UserInfo.m
//  yjw-winner
//
//  Created by 王春辉 on 2018/9/13.
//  Copyright © 2018年 Shanghai decade financial information service co., LTD. All rights reserved.
//

#import "VC_UserInfo.h"
#import "Cell_UserInfo.h"
#import "Model_UserInfo.h"
#import "LocationAlertView.h"


static NSString *identifier = @"user_info_identifier";
@interface VC_UserInfo ()<UITableViewDelegate, UITableViewDataSource, UINavigationControllerDelegate, UIImagePickerControllerDelegate> {
    UITableView *_tableView;
}
@property (nonatomic, strong) UIView *headerView;
@property (nonatomic, strong) UIImageView *headImageView;
@property (nonatomic, strong) NSArray *titleArray;
@property (nonatomic, strong) NSArray *selArray;
@property (nonatomic, strong) Model_UserInfo *userInfomodel;
@end

@implementation VC_UserInfo
- (NSArray *)titleArray {
    if (!_titleArray) {
        _titleArray = @[@"昵称:",
                        @"手机号:",
                        @"地区:"];
    }
    return _titleArray;
}
- (Model_UserInfo *)userInfomodel {
    if (!_userInfomodel) {
        _userInfomodel = [[Model_UserInfo alloc] init];
    }
    return _userInfomodel;
}
- (NSArray *)selArray {
    if (!_selArray) {
        _selArray = @[@[],
                      @[NSStringFromSelector(@selector(userInfoUserName:)),
                        NSStringFromSelector(@selector(userInfoPhoneNumber:)),
                        NSStringFromSelector(@selector(userInfoLocation:))]];
    }
    return _selArray;
}

- (UIView *)headerView  {
    if (!_headerView) {
        _headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.mj_w, 115.0f)];
        _headerView.backgroundColor = MAIN_VC_BACKGROUND_COLOR;
        UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, _headerView.mj_w, 110)];
        view.backgroundColor = [UIColor whiteColor];
        [_headerView addSubview:view];
        UIView *v = [[UIView alloc] init];
        v.bounds = CGRectMake(0, 0, 55, 75);
        v.center = CGPointMake(view.mj_w * 0.5, view.mj_h * 0.5);
        [view addSubview:v];
        self.headImageView.frame = CGRectMake(0, 0, v.mj_w, v.mj_w);
        self.headImageView.layer.cornerRadius = v.mj_w * 0.5;
        [v addSubview:self.headImageView];
        UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, v.mj_w, v.mj_w, v.mj_h - v.mj_w)];
        label.font = [UIFont systemFontOfSize:13];
        label.text = @"设置头像";
        label.textColor = [UIColor blackColor];
        [v addSubview:label];
    }
    return _headerView;
}
- (UIImageView *)headImageView {
    if (!_headImageView) {
        _headImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"un_audio_icon"]];
        _headImageView.layer.masksToBounds = YES;
        _headImageView.contentMode = UIViewContentModeScaleAspectFill;
        _headImageView.userInteractionEnabled = YES;
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(userInfoHeader:)];
        tap.numberOfTapsRequired = 1;
        [_headImageView addGestureRecognizer:tap];
    }
    return _headImageView;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = MAIN_VC_BACKGROUND_COLOR;
    [self initTableView];
    [self initButton];
}
- (void)initButton {
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    button.backgroundColor = MAIN_COLOR;
    [button setTitle:@"保存" forState:UIControlStateNormal];
    [button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [button addTarget:self action:@selector(userInfoSaveButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    button.frame = CGRectMake(50, _tableView.bounds.size.height - 50 - 40, self.view.mj_w - 100, 40);
    button.layer.masksToBounds = YES;
    button.layer.cornerRadius = 4.0f;
    [self.view addSubview:button];
}
- (void)initTableView {
    _tableView = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStylePlain];
    _tableView.showsVerticalScrollIndicator = NO;
    _tableView.showsHorizontalScrollIndicator = NO;
    _tableView.tableFooterView = [UIView new];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    _tableView.backgroundColor = MAIN_VC_BACKGROUND_COLOR;
    _tableView.scrollEnabled = NO;
    _tableView.separatorInset = UIEdgeInsetsMake(0, 10, 0, 10);
    _tableView.tableHeaderView = self.headerView;
    [_tableView registerNib:[UINib nibWithNibName:NSStringFromClass([Cell_UserInfo class]) bundle:[NSBundle mainBundle]] forCellReuseIdentifier:identifier];
    [self.view addSubview:_tableView];
}


#pragma mark --mark UITableViewDelegate UITableViewDataSource

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    Cell_UserInfo *cell = [tableView dequeueReusableCellWithIdentifier:identifier forIndexPath:indexPath];
    if (!cell) {
        cell = [[Cell_UserInfo alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
    }
    if (indexPath.row > 0) {
        cell.detailLabel.textColor = [UIColor grayColor];
    }
    NSString *title = self.titleArray[indexPath.row];
    NSArray *arr = self.userInfomodel.cellDataArray;
    NSString *detail = arr[indexPath.row];
    cell.detailLabel.text = detail;
    cell.titleLabel.text = title;
    return cell;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.titleArray.count;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 49.0f;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    NSArray *sels = self.selArray[1];
    SEL sel = NSSelectorFromString(sels[indexPath.row]);
    if ([self respondsToSelector:sel]) {
        [self performSelector:sel withObject:nil afterDelay:0];
    }
}


#pragma mark --mark EVENT

/**
 修改头像

 @param info info
 */
- (void)userInfoHeader:(id)info {
    [self tokeHeadImageAlert];
}
- (void)tokeHeadImageAlert {
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"" message:@"采集头像" preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
    UIAlertAction *camera = [UIAlertAction actionWithTitle:@"打开相机" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
       // 打开相机
        [self openCamera];
    }];
    UIAlertAction *album = [UIAlertAction actionWithTitle:@"打开相册" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        // 打开相册
        [self openAlbum];
    }];
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
        [alert addAction:camera];
    }
    [alert addAction:album];
    [alert addAction:cancel];
    [self presentViewController:alert animated:YES completion:nil];
}
/**
 修改昵称

 @param info info
 */
- (void)userInfoUserName:(id)info {
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"" message:@"" preferredStyle:UIAlertControllerStyleAlert];
    [alert addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
        textField.placeholder = @"请输入您的昵称...";
        textField.secureTextEntry = NO;
    }];
    [alert addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil]];
    __weak typeof(self) weakself = self;
    [alert addAction:[UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        typeof(weakself) strongself = weakself;
        UITextField *textField = alert.textFields.lastObject;
        @try {
            NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
            if (textField.text.length >= 1) {
                [strongself reloadRowAthIndexPath:indexPath withData:textField.text];
            }
        }
        @catch(NSException *exception) {
            NSLog(@"%@", exception);
        }
    }]];
    [self presentViewController:alert animated:YES completion:nil];

}

/**
 修改电话号码

 @param info info
 */
- (void)userInfoPhoneNumber:(id)info {
    
}

/**
 修改用户所在地区

 @param info info
 */
- (void)userInfoLocation:(id)info {
    
    // 选择地区
    
    UIView *maskView = [[UIView alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    maskView.backgroundColor = [UIColor grayColor];
    maskView.alpha = 0.7;
    [self.view.window addSubview:maskView];
    
    LocationAlertView *alertView = [LocationAlertView alert];
    alertView.backgroundColor = [UIColor whiteColor];
    alertView.frame = CGRectMake(0, [UIScreen mainScreen].bounds.size.height - 232, [UIScreen mainScreen].bounds.size.width, 232);
    [self.view.window addSubview:alertView];
    
    __weak typeof(self) weakself = self;
    __block LocationAlertView *alert = alertView;
    __block UIView *mask = maskView;
    [alertView settingLocationCallBack:^(NSString *location, LocationAlertButtonType type) {
        [alert removeFromSuperview];
        [mask removeFromSuperview];
        [weakself setLocation:location];
    }];
}
- (void)setLocation:(NSString *)location {
    self.userInfomodel.location = location;
    [_tableView reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:2 inSection:0]] withRowAnimation:UITableViewRowAnimationNone];
}

/**
 保存修改信息

 @param sender sender
 */
- (void)userInfoSaveButtonClick:(UIButton *)sender {
    // 上传 昵称 & 地区
    [MBProgressHUD showSuccess:@"上传并保存数据"];
}

/**
 刷新cell上的数据

 @param indexPath indexPath
 @param data data
 */
- (void)reloadRowAthIndexPath:(NSIndexPath *)indexPath withData:(NSString *)data {
    self.userInfomodel.userName = data;
    [_tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
}


#pragma mark --mark 头像

- (void)openCamera {
    
    /* 资源类型为照相机 */
    UIImagePickerControllerSourceType sourceType = UIImagePickerControllerSourceTypeCamera;
    
    UIImagePickerControllerQualityType qualityType = UIImagePickerControllerQualityTypeHigh;
    /* 判断是否有相机 */
    if ([UIImagePickerController isSourceTypeAvailable: UIImagePickerControllerSourceTypeCamera])
    {
        UIImagePickerController *picker = [[UIImagePickerController alloc] init];
        picker.delegate = self;
        
        /* 设置拍照后的图片可被编辑 */
        picker.allowsEditing = YES;
        
        /* 资源类型为照相机 */
        picker.sourceType = sourceType;
        
        /* 品质为高 */
        picker.videoQuality = qualityType;
        [self presentViewController:picker animated:YES completion:nil];
    }
    else
    {
        NSLog(@"该设备无摄像头");
    }
}
- (void)openAlbum {
    UIImagePickerController *picker = [[UIImagePickerController alloc] init];
    
    /* 资源类型为图片库 */
    picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    picker.delegate = self;
    
    /* 设置选择后的图片可被编辑 */
    picker.allowsEditing = YES;
    [self presentViewController:picker animated:YES completion:nil];
}

#pragma mark --mark UINavigationControllerDelegate, UIImagePickerControllerDelegate

/**
 *  图像选取器的委托方法，选完图片后回调该方法
 */
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingImage:(UIImage *)image editingInfo:(NSDictionary *)editingInfo{
    
    /* 当图片不为空时显示图片并保存图片 */
    if (image != nil)
    {
        /* 图片显示在界面上 */
        // [_iconButton setBackgroundImage:image forState:UIControlStateNormal]; // 显示在按钮上
        self.headImageView.image = image;
        
        /* 以下是保存文件到沙盒路径下 */
        /* 把图片转成NSData类型的数据来保存文件 */
        NSData *data;
        
        /* 判断图片是不是png格式的文件 */
        if (UIImagePNGRepresentation(image))
        {
            /* 返回为png图像 */
            data = UIImagePNGRepresentation(image);
        }
        else
        {
            /* 返回为JPEG图像 */
            data = UIImageJPEGRepresentation(image, 1.0);
        }
        
        /* 保存 */
//        [[NSFileManager defaultManager] createFileAtPath:self.imagePath contents:data attributes:nil];
    }
    [picker dismissViewControllerAnimated:YES completion:nil];
}
@end
